package com.kmis.utils;

import cn.hutool.core.codec.Base64;
import com.kmis.common.constant.JwtConstant;
import com.kmis.web.CheckResult;
import io.jsonwebtoken.*;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

/**
 * @author moc
 */
public class JwtUtil {

    /**
     * 签发jwt
     * @param id
     * @param subject
     * @param ttlMillis
     * @return
     */
    public static String createJWT(String id,String subject,long ttlMillis){
        SignatureAlgorithm algorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        SecretKey secretKey = generalKey();
        JwtBuilder builder = Jwts.builder()
                .setId(id)
                //主题
                .setSubject(subject)
                //签发人
                .setIssuer("moc")
                //签发时间
                .setIssuedAt(now)
                //签名算法和密钥
                .signWith(algorithm,secretKey);
        if(ttlMillis>=0){
            long expMillis = nowMillis+ttlMillis;
            Date expDate = new Date(expMillis);
            //过期时间
            builder.setExpiration(expDate);
        }
        return builder.compact();
    }

    /**
     * 生成token
     * @param username
     * @return
     */
    public static String genJwtToken(String username){
        return createJWT(username,username,60*60*1000);
    }


    /**
     * 验证token
     * @param jwtStr
     * @return
     */
    public static CheckResult validateJWT(String jwtStr){
        CheckResult result = new CheckResult();
        Claims claims = null;
        try{
            claims = parseJwt(jwtStr);
            result.setSuccess(true);
            result.setClaims(claims);
        }catch(ExpiredJwtException e){
            result.setErrorCode(JwtConstant.JWT_ERROR_EXPIRE);
            result.setSuccess(false);
        }catch (SignatureException e){
            result.setErrorCode(JwtConstant.JWT_ERROR_FAIL);
            result.setSuccess(false);
        }catch(Exception e){
            result.setErrorCode(JwtConstant.JWT_ERROR_FAIL);
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 解析token字符串
     * @param jwt
     * @return
     */
    public static Claims parseJwt(String jwt) {
        SecretKey secretKey = generalKey();
        return Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
    }

    /**
     * 生成加密key
     * @return key
     */
    private static SecretKey generalKey() {
        byte[] encodedKey = Base64.decode(JwtConstant.JWT_SECERT);
        SecretKey key =  new SecretKeySpec(encodedKey,0,encodedKey.length,"AES");
        return key;
    }

    public static void main(String[] args) {

    }
}

